var AldeasInfantiles = angular.module("AldeasInfantiles", []);

AldeasInfantiles.controller("Users", function($scope, $http, $timeout) {

  $scope.countries = []; //Array with all registred countries in the database
  $scope.dorps = []; //Array with all registred dorps in the database
  $scope.typeusers = []; //Array with all users type in the database
  $scope.users = []; //Array with all registred users in the database
  $scope.user = {}; //User object
  $scope.selectedType = ""; //Selected user type value
  $scope.selectedCountry = ""; //Selected user country value
  $scope.selectedDorp = ""; //Selected user dorp value
  $scope.selectedState = ""; //Selected user state value
  $scope.hiddenClass = "hidden"; //Used to show or hide the error message in the UI
  $scope.alertClass = ""; //Used to display a message in the UI
  $scope.errorMessage = ""; //Used to change the class of the message div in the UI

  //Requests all countries
  $scope.requestCountries = function () {
    $http({
          method: 'POST', 
          url: currentPath + 'countries/returncountries/'
        }).
        success(function(data) {
          $scope.countries = data;
          $scope.selectedCountry = data[0].id_pais;
          $scope.requestDorps(); 
        }).
        error(function(data, status) {
          console.log(e.message);
        });
  };

  //Request all dorps
  $scope.requestDorps = function () {
    $http({
          method: 'POST', 
          url: currentPath + 'dorps/returndorpsbycountry/' + $scope.selectedCountry
        }).
        success(function(data) {
          $scope.dorps = data;
          $scope.selectedDorp = data[0].id_programa;
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };

  //Request all users type
  $scope.requestTypeUsers = function () {
    $http({
          method: 'POST', 
          url: currentPath + 'users/returntypeusers/'
        }).
        success(function(data) {
          $scope.typeusers = data;
          $scope.selectedType = data[0].id_tipousuario;
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };

  //Displays all users in the UI
  $scope.showUsers = function () {
    $http({
            async: false,
            method: 'POST', 
            url: currentPath + 'users/returnallusers/'
        }).
        success(function(data) {
          $scope.users = data;
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };

  //Receives the id of an user to get the information from the DB
  $scope.getUserId = function (user) {
    var id = user.id_usuario;
    $scope.resetForm();
    $scope.hiddenClass = "hidden";
    $http({
            method: 'POST', 
            url: currentPath + 'users/returnuserbyid/' + id
        }).
        success(function(data) {
          $scope.user.username = data[0].ds_usuario;
          $scope.user.usernick = data[0].ds_nick;
          $scope.selectedType = data[0].id_tipousuario;
          $scope.selectedCountry = data[0].id_pais;
          $scope.selectedDorp = data[0].id_programa;
          $scope.selectedState = data[0].estado;
          $('#modal-users').modal('hide');
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };

  //Gets the values of the UI inputs
  $scope.getParams = function ($user) {
    $params = $.param({
      'username': $user.username,
      'usernick': $user.usernick,
      'userpass': $user.userpass,
      'usertype': $scope.selectedType,
      'usercountry': $scope.selectedCountry,
      'userdorp': $scope.selectedDorp,
      'userstate': $scope.selectedState
    })
    $scope.saveUser($params);
  };

  //Saves the user information in the database
  $scope.saveUser = function ($params) {
    $http({
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            url: currentPath + 'users/saveuser/',
            method: 'POST', 
            data: $params            
        }).
        success(function(data, status) {
          if(data.response == "success"){
            $scope.errorMessage = "Datos guardatos correctamente";
            $scope.hiddenClass = "";
            $scope.alertClass = "alert-success";
            $scope.resetForm();
          }else if(data.response == "incomplete_form"){
            $scope.hiddenClass = "";
            $scope.alertClass = "alert-danger";
            $scope.errorMessage = "Debes escribir todos los datos del formulario.";
          }else if(data.response == "failed"){
            $scope.hiddenClass = "";
            $scope.alertClass = "alert-danger";
            $scope.errorMessage = "Algo fallo al guardar los datos, intentalo de nuevo.";
          }
        }).
        error(function(data, status) {
          $scope.hiddenClass = "";
          $scope.errorMessage = data;
        });
  };

  $scope.resetForm = function() {
    $scope.user.username = "";
    $scope.user.usernick = "";
    $scope.user.userpass = "";
    $scope.selectedType = 1;
    $scope.selectedCountry = 1;
    $scope.selectedState = 1;
    $timeout(countUp, 5000);
  };

  var countUp = function() {
    $scope.hiddenClass = "hidden";
  }

  $scope.setDefaultSettings = function () {
    $scope.resetForm();
    $scope.requestCountries(); 
    $scope.requestTypeUsers();
    $scope.selectedState = 1;
  }

  $scope.setDefaultSettings();

});